#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>

int main(int argc, char const *argv[])
{
	// 创建子进程
	pid_t son = fork();
	if(son > 0) // 父进程
	{
		pid_t son1 = fork();
		if(son1 > 0)
		{
			sleep(1);
			printf("我是父进程\n");
			printf("当前的pid=%d\n", getpid());
			printf("当前的父进程的pid=%d\n", getppid());
			int status;
			// int ret1 = waitpid(-1, &status, 0); // 获取子进程的退出值(等价wait(&status))
			// int ret1 = waitpid(-1, &status, WNOHANG); // 非阻塞等待
			int ret1 = waitpid(son1, &status, 0); // 指定等待son1子进程
			printf("ret1=%d\n", ret1);
			// 判断子进程是否为正常退出
			if(WIFEXITED(status))
			{
				printf("当前子进程是正常退出\n");
				printf("子进程的退出值=%d\n", WEXITSTATUS(status));
			}
		}
		else if(son1 == 0) // 子进程
		{
			printf("我是子进程\n");
			printf("当前的pid=%d\n", getpid());
			printf("当前的父进程的pid=%d\n", getppid());
			exit(17); 
		}
	}
	else if(son == 0) // 子进程
	{
		printf("我是子进程\n");
		printf("当前的pid=%d\n", getpid());
		printf("当前的父进程的pid=%d\n", getppid());
		exit(15);
	}
	
	return 0;
}
